<template>
    <div>
        <app-head></app-head>
        <app-body>
            <div class="order-page-container">
                <div class="idle-info-container">
                    <div class="idle-info-title">{{orderInfo.userId==userId?'商品名称':'商品名称'}}：{{orderInfo.idleItem && orderInfo.idleItem.idleName || ''}}</div>
                    <div class="idle-info-price">￥{{orderInfo.orderPrice}}</div>
                </div>
                <div class="address-container" :style="orderInfo.userId==userId&&orderInfo.orderStatus===0">
                    <div class="address-title">收货地址: {{addressInfo.consigneeName}} {{addressInfo.consigneePhone}}</div>
                    <div class="address-detials">{{addressInfo.detailAddress}}</div>
                    <el-button v-if="!addressInfo.detailAddress && orderInfo.orderStatus === 0" @click.stop="selectAddressDialog" type="primary" plain>选择收货地址</el-button>
                </div>
                <el-dialog
                    title="选择地址"
                    :visible.sync="addressDialogVisible"
                    width="800px">
                    <el-table
                        stripe
                        empty-text="无地址信息，请先在个人中心添加地址"
                        :data="addressData"
                        style="width: 100%">
                        <el-table-column
                            prop="consigneeName"
                            label="收货人姓名"
                            width="120">
                        </el-table-column>
                        <el-table-column
                            prop="consigneePhone"
                            label="手机号"
                            width="140">
                        </el-table-column>
                        <el-table-column
                            prop="detailAddressText"
                            label="地址">
                        </el-table-column>
                        <el-table-column label=" " width="120">
                            <template slot-scope="scope">
                                <el-button
                                    size="mini"
                                    @click="selectAddress(scope.$index, scope.row)">选择
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-dialog>
                <div class="order-info-container">
                    <div class="order-info-title">订单信息（{{orderStatus[orderInfo.orderStatus]}}）：</div>
                    <div class="order-info-item">编号：{{orderInfo.orderNumber}}</div>
                    <div class="order-info-item">支付状态：{{orderInfo.orderStatus === 4 ? '已取消' : (orderInfo.paymentStatus===0?'未支付':'已支付')}}</div>
                    <div class="order-info-item">支付方式：{{orderInfo.orderStatus === 4 ? '已取消' : orderInfo.paymentWay}}</div>
                    <div class="order-info-item">创建时间：{{orderInfo.createTime.substring(0, 10) + ' ' +
                    orderInfo.createTime.substring(11, 19)}}
                    </div>
                    <div class="order-info-item">支付时间：{{orderInfo.paymentTime?orderInfo.paymentTime.substring(0, 10) + ' ' +
                        orderInfo.paymentTime.substring(11, 19):''}}
                    </div>
                </div>
                <div class="menu">
                    <!-- 状态为0时显示取消支付和立即支付按钮 -->
                    <el-button v-if="orderInfo.orderStatus === 0"
                               type="danger"
                               plain
                               @click.stop="handleCancelOrder()">取消支付</el-button>
                    <el-button v-if="orderInfo.orderStatus === 0"
                               type="primary"
                               plain
                               @click="handleConfirmPayment"
                               :disabled="!addressInfo.detailAddress">立即支付</el-button>

                    <!-- 卖家且订单状态为待发货时显示发货按钮 -->
                    <el-button v-if="Number(userId) === Number(orderInfo.sellerId) && orderInfo.orderStatus === 1"
                               type="primary"
                               plain
                               @click="changeOrderStatus(2, orderInfo)">呼叫骑手</el-button>

                    <el-button v-if="orderInfo.userId === userId && orderInfo.orderStatus === 2"
                               type="primary"
                               plain
                               @click="changeOrderStatus(3, orderInfo)">确认收货</el-button>

                    <el-button v-if="orderInfo.orderStatus===3 || orderInfo.orderStatus===4"
                               type="danger"
                               plain
                               @click="handleDeleteOrder">删除订单</el-button>
                </div>
            </div>
            <app-foot></app-foot>
        </app-body>
    </div>
</template>

<script>
import AppHead from '../common/AppHeader.vue';
import AppBody from '../common/AppPageBody.vue'
import AppFoot from '../common/AppFoot.vue'

export default {
    name: "order",
    components: {
        AppHead,
        AppBody,
        AppFoot
    },
    data() {
        // 从 localStorage 获取用户信息
        const userInfo = JSON.parse(localStorage.getItem('userInfo'));
        let currentUserId = null;

        // 如果localStorage中没有用户信息，尝试从token中获取
        if (!userInfo || !userInfo.userId) {
            const token = localStorage.getItem('token');
            if (token) {
                try {
                    // JWT token的格式是 header.payload.signature
                    const payload = JSON.parse(atob(token.split('.')[1]));
                    currentUserId = Number(payload.sub); // sub 是 JWT 中存储用户ID的字段
                } catch (e) {
                    console.error('解析token失败:', e);
                }
            }
        } else {
            currentUserId = Number(userInfo.userId);
        }

        return {
            addressDialogVisible:false,
            addressData: [],
            orderStatus: ['待付款', '待发货', '待收货', '已完成', '已取消'],
            orderInfo: {
                createTime: "",
                id: 0,
                idleId: 0,
                sellerId: '',
                idleItem: {
                    id: '',
                    idleName: '',
                    idleDetails: '',
                    pictureList: [],
                    idlePrice: 0,
                    idlePlace: '',
                    idleLabel: '',
                    idleStatus: -1,
                },
                orderNumber: "",
                orderPrice: 0,
                orderStatus: 0,
                paymentStatus: 0,
                paymentTime: "",
                paymentWay: "",
                userId: 0
            },
            addressInfo: {
                id:'',
                update:false,
                consigneeName: '',
                consigneePhone: '',
                detailAddress: ''
            },
            userId: currentUserId
        };
    },
    created() {
        // 如果还是没有获取到用户ID，则从API获取
        if (this.userId === null) {
            this.$api.getUserInfo().then(res => {
                if (res.code === 200 && res.data) {
                    this.userId = Number(res.data.userId);
                    console.log('从API获取的用户ID:', this.userId);
                } else {
                    console.error('获取用户信息失败:', res.message);
                    this.$message.error('获取用户信息失败，请重新登录');
                    this.$router.push('/login');
                }
            }).catch(err => {
                console.error('获取用户信息失败:', err);
                this.$message.error('获取用户信息失败，请重新登录');
                this.$router.push('/login');
            });
        }

        console.log('当前用户ID:', this.userId);

        // 获取订单ID
        const orderId = this.$route.query.id;
        if (!orderId) {
            this.$message.error('订单ID不存在');
            return;
        }

        // 获取订单详情
        this.$api.getOrderDetail(orderId).then(res => {
            if (res.code === 200 && res.data) {
                const orderData = res.data;
                console.log('获取到的订单数据:', orderData);

                // 确保 idleItem 存在并且包含必要的属性
                const idleItem = orderData.idleItem || {};

                // 处理后端返回的商品数据
                const processedIdleItem = {
                    ...idleItem,
                    id: idleItem.id || idleItem.productId || '',
                    idleName: idleItem.idleName || idleItem.productName || '',  // 支持两种属性名
                    idleDetails: idleItem.idleDetails || idleItem.description || '',
                    pictureList: idleItem.pictureList || (idleItem.imageUrl ? [idleItem.imageUrl] : []),  // 支持单图片或图片列表
                    idlePrice: idleItem.idlePrice || idleItem.price || 0,
                    idlePlace: idleItem.idlePlace || idleItem.place || '',
                    idleLabel: idleItem.idleLabel || idleItem.label || '',
                    idleStatus: Number(idleItem.idleStatus || idleItem.status || -1),
                    userId: Number(orderData.sellerId || 0)  // 设置商品所有者ID为卖家ID
                };

                // 更新订单信息
                this.orderInfo = {
                    ...orderData,
                    orderStatus: Number(orderData.orderStatus || 0),
                    paymentStatus: Number(orderData.paymentStatus || 0),
                    userId: Number(orderData.buyerId || 0),  // 买家ID
                    sellerId: Number(orderData.sellerId || 0),  // 卖家ID
                    idleItem: processedIdleItem
                };

                // 如果订单已支付，确保订单状态正确
                if (this.orderInfo.paymentStatus === 1 && this.orderInfo.orderStatus === 0) {
                    this.orderInfo.orderStatus = 1;
                }

                // 更新地址信息
                if (orderData.orderAddress) {
                    this.addressInfo = {
                        id: orderData.orderAddress.id || '',
                        update: true,
                        consigneeName: orderData.orderAddress.consigneeName || '',
                        consigneePhone: orderData.orderAddress.consigneePhone || '',
                        detailAddress: orderData.orderAddress.province && orderData.orderAddress.city && orderData.orderAddress.district ?
                            `${orderData.orderAddress.province}${orderData.orderAddress.city}${orderData.orderAddress.district}${orderData.orderAddress.detailAddress}` : ''
                    };
                }

                console.log('处理后的订单信息:', {
                    currentUserId: this.userId,
                    buyerId: this.orderInfo.userId,
                    sellerId: this.orderInfo.sellerId,
                    orderStatus: this.orderInfo.orderStatus,
                    idleItem: this.orderInfo.idleItem
                });
            } else {
                this.$message.error(res.message || '获取订单信息失败');
            }
        }).catch(err => {
            console.error('获取订单信息失败:', err);
            this.$message.error('网络错误，请稍后重试');
        });

        // 获取用户地址列表
        this.getAddressData();
    },
    methods: {
        toDetails(id) {
            this.$router.replace({path: 'details', query: {id: id}});
        },
        selectAddressDialog(){
            if(this.orderInfo.userId == this.userId && this.orderInfo.orderStatus === 0){
                this.addressDialogVisible = true;
                if(this.addressData.length === 0){
                    this.getAddressData();
                }
            }
        },
        getAddressData() {
            this.$api.getAddress().then(res => {
                if (res.code === 200) {
                    let data = res.data;
                    for (let i = 0; i < data.length; i++) {
                        data[i].detailAddressText = data[i].provinceName + data[i].cityName + data[i].regionName + data[i].detailAddress;
                    }
                    this.addressData = data;

                    // 如果有默认地址，自动选择
                    if (!this.addressInfo.update) {
                        const defaultAddr = data.find(addr => addr.defaultFlag);
                        if (defaultAddr) {
                            this.selectAddress(0, defaultAddr);
                        }
                    }
                }
            }).catch(err => {
                console.error('获取地址列表失败:', err);
                this.$message.error('获取地址列表失败');
            });
        },
        selectAddress(index, item) {
            this.addressDialogVisible = false;
            this.addressInfo = {
                consigneeName: item.consigneeName,
                consigneePhone: item.consigneePhone,
                detailAddress: item.detailAddressText,
                update: true
            };

            if (this.orderInfo.id) {
                if (this.addressInfo.id) {
                    // 更新已有地址
                    this.$api.updateOrderAddress({
                        id: this.addressInfo.id,
                        orderId: this.orderInfo.id,
                        consigneeName: item.consigneeName,
                        consigneePhone: item.consigneePhone,
                        detailAddress: item.detailAddressText
                    }).then(res => {
                        if (res.code !== 200) {
                            this.$message.error(res.message || '更新地址失败');
                        }
                    });
                } else {
                    // 添加新地址
                    this.$api.addOrderAddress({
                        orderId: this.orderInfo.id,
                        consigneeName: item.consigneeName,
                        consigneePhone: item.consigneePhone,
                        detailAddress: item.detailAddressText
                    }).then(res => {
                        if (res.code === 200) {
                            this.addressInfo.id = res.data.id;
                        } else {
                            this.$message.error(res.message || '添加地址失败');
                        }
                    });
                }
            }
        },
        handleDeleteOrder() {
            this.$confirm('确定要删除该订单吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$api.deleteOrder(this.orderInfo.id).then(res => {
                    if (res.code === 200) {
                        this.$message.success('订单删除成功');
                        // 跳转回订单列表页
                        this.$router.push('/me');
                    } else {
                        this.$message.error(res.message || '删除失败');
                    }
                }).catch(err => {
                    console.error('删除订单失败:', err);
                    this.$message.error('网络错误，请稍后重试');
                });
            }).catch(() => {
                this.$message.info('已取消删除');
            });
        },
        changeOrderStatus(status, orderInfo) {
            const statusText = {
                2: '呼叫骑手',
                3: '确认收货'
            }[status] || '更新状态';

            this.$confirm(`确认要${statusText}吗？`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                // 如果是发货操作，使用与支付相同的逻辑
                if (status === 2) {
                    const updateData = {
                        id: orderInfo.id,
                        orderStatus: status
                    };
                    console.log('发送发货请求数据:', updateData);

                    this.$api.updateOrderStatus(updateData).then(res => {
                        console.log('发货请求响应:', res);
                        if (res.code === 200) {
                            // 确保后端更新成功后再获取新数据
                            this.$api.getOrderDetail(orderInfo.id).then(detailRes => {
                                if (detailRes.code === 200 && detailRes.data) {
                                    const newOrderData = detailRes.data;
                                    // 强制更新订单状态为已发货
                                    this.orderInfo = {
                                        ...newOrderData,
                                        orderStatus: 2,
                                        paymentStatus: Number(newOrderData.paymentStatus || 0),
                                        sellerId: Number(newOrderData.sellerId || 0)
                                    };
                                    this.$message.success('发货成功');
                                } else {
                                    this.$message.error('获取最新订单数据失败');
                                }
                            });
                        } else {
                            this.$message.error(res.message || '发货失败');
                        }
                    }).catch(err => {
                        console.error('发货失败:', err);
                        this.$message.error('网络错误，请稍后重试');
                    });
                } else {
                    // 其他状态更新的处理
                    this.$api.updateOrderStatus({
                        id: orderInfo.id,
                        orderStatus: status
                    }).then(res => {
                        if (res.code === 200) {
                            this.$message.success(`${statusText}成功`);
                            this.refreshOrderData();
                        } else {
                            this.$message.error(res.message || `${statusText}失败`);
                        }
                    }).catch(err => {
                        console.error('更新状态失败:', err);
                        this.$message.error('网络错误，请稍后重试');
                    });
                }
            }).catch(() => {
                this.$message.info('已取消操作');
            });
        },

        handleCancelOrder() {
            // 验证订单ID
            const targetOrderId = this.orderInfo.id;
            if (!targetOrderId) {
                this.$message.error('订单ID不存在，无法取消');
                return;
            }

            // 验证订单状态
            if (this.orderInfo.orderStatus === 4) {
                this.$message.warning('订单已取消');
                return;
            }

            this.$confirm('确定要取消订单吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$api.updateOrderStatus({
                    id: targetOrderId,
                    orderStatus: 4
                }).then(res => {
                    if (res.code === 200) {
                        this.$message.success('订单已取消');
                        // 刷新页面数据
                        this.refreshOrderData();
                    } else {
                        this.$message.error(res.message || '取消订单失败');
                    }
                }).catch(err => {
                    console.error('取消订单失败:', err);
                    this.$message.error('网络错误，请稍后重试');
                });
            }).catch(() => {
                this.$message.info('已取消操作');
            });
        },

        handleConfirmPayment() {
            if (!this.addressInfo.detailAddress) {
                this.$message.error('请先选择收货地址');
                return;
            }

            this.$confirm('确认要支付该订单吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                const paymentData = {
                    paymentWay: '在线支付',
                    transactionId: 'TX' + Date.now()
                };

                this.$api.payOrder(this.orderInfo.id, paymentData).then(res => {
                    if (res.code === 200) {
                        this.$message.success('支付成功');
                        console.log("打印订单信息：",res);
                        // 更新订单信息
                        // this.orderInfo = res.data;
                        // 刷新页面数据
                        this.refreshOrderData();
                    } else {
                        this.$message.error(res.message || '支付失败');
                    }
                }).catch(err => {
                    console.error('支付失败:', err);
                    this.$message.error('网络错误，请稍后重试');
                });
            }).catch(() => {
                this.$message.info('已取消支付');
            });
        },
        // 刷新订单数据
        refreshOrderData() {
            this.$api.getOrderDetail(this.orderInfo.id).then(res => {
                if (res.code === 200 && res.data) {
                    const orderData = res.data;
                    console.log('刷新获取到的订单数据:', orderData);

                    // 更新订单信息，保持当前用户ID不变（因为是从localStorage获取的）
                    this.orderInfo = {
                        ...orderData,
                        orderStatus: Number(orderData.orderStatus || 0),
                        paymentStatus: Number(orderData.paymentStatus || 0),
                        sellerId: Number(orderData.sellerId || 0),  // 商品卖家ID
                        idleItem: {
                            ...orderData.idleItem,
                            userId: Number(orderData.sellerId || 0)
                        }
                    };

                    console.log('更新后的订单状态:', this.orderInfo.orderStatus);

                    // 如果订单已支付，确保订单状态正确
                    if (this.orderInfo.paymentStatus === 1 && this.orderInfo.orderStatus === 0) {
                        this.orderInfo.orderStatus = 1;
                    }
                } else {
                    this.$message.error(res.message || '获取订单信息失败');
                }
            }).catch(err => {
                console.error('获取订单信息失败:', err);
                this.$message.error('网络错误，请稍后重试');
            });
        }
    }
}
</script>

<style scoped>
.order-page-container {
    min-height: 85vh;
}

.idle-info-container {
    width: 100%;
    display: flex;
    border-bottom: 20px solid #f6f6f6;
    padding: 20px;
}

.idle-info-title {
    font-size: 18px;
    font-weight: 600;
    max-width: 750px;
    margin-left: 10px;
}

.idle-info-price {
    font-size: 18px;
    color: red;
    margin-left: 10px;
}

.address-container {
    min-height: 60px;
    padding: 20px;
    border-bottom: 20px solid #f6f6f6;

}

.address-title {
    font-size: 18px;
    font-weight: 600;
    margin-bottom: 10px;
}

.address-detials {
    font-size: 16px;
    color: #444444;
}

.order-info-container {
    padding: 20px;
}

.order-info-item {
    margin: 10px 0;
    font-size: 14px;
    color: #444444;
}

.disabled-button {
    opacity: 0.6;
    cursor: not-allowed;
}

.menu {
    margin-left: 20px;
    margin-bottom: 20px;
}

.menu .el-button {
    margin-right: 10px;
}
</style>